//
//  TigerViewController.m
//  Tiger
//
//  Created by King on 11-9-9.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "TigerViewController.h"
#import "InfoViewController.h"
#import "ProductListViewController.h"
#import <QuartzCore/QuartzCore.h>


/*@interface CUILabel(pri) 
    - (UIImage *)gradientImage;
@end

@implementation CUILabel

-(void) cSetText:(NSString*)atext{
    self.text =atext;
    self.textColor = [UIColor colorWithPatternImage:[self gradientImage]];
}

-(void) dealloc{
    [super dealloc];
}



- (UIImage *)gradientImage
{
    CGSize textSize = [self.text sizeWithFont:[UIFont systemFontOfSize:60.f]];
    CGFloat width = textSize.width;         // max 1024 due to Core Graphics limitations
    CGFloat height = textSize.height;       // max 1024 due to Core Graphics limitations
    
    // create a new bitmap image context
    UIGraphicsBeginImageContext(CGSizeMake(width, height));
    
    // get context
    CGContextRef context = UIGraphicsGetCurrentContext();       
    
    // push context to make it current (need to do this manually because we are not drawing in a UIView)
    UIGraphicsPushContext(context);                             
    
    //draw gradient    
    CGGradientRef glossGradient;
    CGColorSpaceRef rgbColorspace;
    size_t num_locations = 2;
    CGFloat locations[2] = { 0.0, 1.0 };
    CGFloat components[8] = { 1.0, 1.0, 1.0, 1.0,  // Start color
        58/255.f, 58/255.f, 58/255.f, 1.0 }; // End color
    rgbColorspace = CGColorSpaceCreateDeviceRGB();
    glossGradient = CGGradientCreateWithColorComponents(rgbColorspace, components, locations, num_locations);
    CGPoint topCenter = CGPointMake(0, 0);
    CGPoint bottomCenter = CGPointMake(0, textSize.height);
    CGContextDrawLinearGradient(context, glossGradient, topCenter, bottomCenter, 0);
    
    CGGradientRelease(glossGradient);
    CGColorSpaceRelease(rgbColorspace); 
    
    // pop context 
    UIGraphicsPopContext();                             
    
    // get a UIImage from the image context
    UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // clean up drawing environment
    UIGraphicsEndImageContext();
    
    return  gradientImage;
}
@end*/

@implementation TigerViewController

@synthesize parsedDataArray;
@synthesize isLoad;

static NSString *kName =			@"name";
static NSString *kCateID =			@"cateID";

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
   // [super viewDidLoad];
	isLoad = NO;
	
	UIButton *infButton = [UIButton buttonWithType:UIButtonTypeInfoDark];
    [infButton setBackgroundImage:[UIImage imageNamed:@"infobar.png"] forState:UIControlStateNormal];
	[infButton addTarget:self action:@selector(infButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
	UIBarButtonItem *infoBarBtn = [[UIBarButtonItem alloc] initWithCustomView:infButton];
	self.navigationItem.rightBarButtonItem = infoBarBtn;	
	[infButton release];
	[infoBarBtn release];
	
//	activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
//	activity.hidesWhenStopped = YES;
//	[self.view addSubview:activity];
//	activity.center = self.view.center;
    if([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"] forBarMetrics: UIBarMetricsDefault];
        self.navigationController.navigationBar.clipsToBounds = YES;
        
    }
	[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"top.png"]];
	self.navigationController.navigationBar.tintColor =  [UIColor colorWithRed:33.0/255 green:32.0/255 blue:32.0/255 alpha:1.0];
	
	NSMutableArray *array = [[NSMutableArray alloc] init];
	self.parsedDataArray = array;
	[array release];
    
    
    p_NewAniVC = [[NewAniView alloc] initWithFrame:CGRectMake(0, 0, 320, 392)];
    [p_NewAniVC setClipsToBounds:YES];
    p_NewAniVC.userInteractionEnabled =YES;
    p_NewAniVC.m_Delegate = self;
	[self.view addSubview:p_NewAniVC];
	[self sendRequestPayInfo];
	
}

-(void)viewDidAppear:(BOOL)animated{
	
	[super viewDidAppear:animated];

}

-(void)sendRequestPayInfo
{
	[activity startAnimating];
	NSURL* serverURL = [NSURL URLWithString:URL_ProductCategory];
	ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:serverURL];
	request.tag = -1;
	[request setValidatesSecureCertificate:NO];
	[request setDelegate:self];
	[request startAsynchronous];
	
}

- (IBAction)infButtonTapped:(id)sender{

	InfoViewController *infoViewController = [[InfoViewController alloc] initWithNibName:@"InfoViewController" bundle:nil];
	[self presentModalViewController:infoViewController animated:YES];
	[infoViewController release];
	
}



/*- (void)openFlowView:(AFOpenFlowView *)openFlowView requestImageForIndex:(int)index{
	NSLog(@"request image for index called");
}

- (void)openFlowView:(AFOpenFlowView *)openFlowView selectionDidChange:(int)index
{
	NSDictionary *dict = [parsedDataArray objectAtIndex:index];
    [textLabel cSetText:[dict objectForKey:kName]];
}


//openflow点击图片触发事件
- (void)openFlowView:(AFOpenFlowView *)openFlowView singleTaped:(int)index{
	
	NSDictionary *dict = [parsedDataArray objectAtIndex:index];	
	ProductListViewController *viewController = [[ProductListViewController alloc] initWithNibName:@"ProductListViewController" bundle:nil];
	viewController.hidesBottomBarWhenPushed = YES;
	viewController.cateID = [[dict objectForKey:kCateID] intValue];
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"产品分类" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	//导航自带的动画
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
}*/

- (UIImage *)defaultImage{
	//NSLog(@"default call");
	return [UIImage imageNamed:@"Default.png"];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
}

- (void)grabImageURLString:(NSString *)urlStr requestTag:(int)tag
{
    NSLog(@"img request =%@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
	request.tag = tag;
    [request setDelegate:self];
    [request startAsynchronous];
}

-(void)setImagesForDataIndex:(int)index {
	for (int i=0; i<[parsedDataArray count]; i++) {
		NSMutableDictionary *dict = [parsedDataArray objectAtIndex:i];
		UIImage *image = [dict objectForKey:@"image"];
		if (!image) {
			return;
		}
	}
	
	for (int i=0; i<[parsedDataArray count]; i++) {
		NSMutableDictionary *dict = [parsedDataArray objectAtIndex:i];
		UIImage *image = [dict objectForKey:@"image"];
        if (!image) {
            continue;
        }
		[p_NewAniVC setImage:image forIndex:i];
	}
    isLoad = YES;
	
}

//- (void)alphaAnimation
//{
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
//    [UIView setAnimationDuration:.5];
//	
//	[afview setFrame:CGRectMake(-4, -10, 320, 405)];
//    [UIView commitAnimations];
//    
//}

- (void)requestFinished:(ASIHTTPRequest *)request
{
	NSData *responseData = [request responseData];
	NSString *responseStr = [[[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding] autorelease];
    if (activity) {
        [activity stopAnimating];
        [activity removeFromSuperview];
        [activity release];
        activity =nil;
    }
    
	if (request.tag < 0) {
		NSDictionary *dict = [responseStr JSONValue];
		self.parsedDataArray = [dict objectForKey:@"items"];
		NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectory = [paths objectAtIndex:0];
		NSString *path = [documentsDirectory stringByAppendingPathComponent:@"productData.plist"];
		
		NSFileManager* fm = [NSFileManager defaultManager];
		[fm createFileAtPath:path contents:nil attributes:nil];        
		[dict writeToFile:path atomically:YES];
		
        [p_NewAniVC setDataForMyViews:parsedDataArray];
        
		for (int i=0; i<[parsedDataArray count]; i++) {
			NSDictionary *dict = [parsedDataArray objectAtIndex:i];
			[self grabImageURLString:[dict objectForKey:@"picUrl"] requestTag:i];
		}

        
	} 
	else 
	{
		UIImage *image = [[UIImage alloc] initWithData:responseData];
		NSMutableDictionary *dict = [parsedDataArray objectAtIndex:request.tag];
		if (image) {
			[dict setObject:image forKey:@"image"];
		} 
		else 
		{
			[dict setObject:[UIImage imageNamed:@"Placeholder.png"] forKey:@"image"];
		}
		
		[self setImagesForDataIndex:request.tag];
	}
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	[activity stopAnimating];
    if (request) {
        if (request.tag >0 && request.tag<[parsedDataArray count]) {
            NSMutableDictionary *dict = [parsedDataArray objectAtIndex:request.tag];
            [dict setObject:[UIImage imageNamed:@"Placeholder.png"] forKey:@"image"];
            [self setImagesForDataIndex:request.tag];
        }
    }
	UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"无可用的网络连接" delegate:self 
										   cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
	[alert addButtonWithTitle:@"确定"];
	[alert show];
	
	
}

- (void)dealloc {
    [p_NewAniVC release];
	[parsedDataArray release];
	[super dealloc];
}



#pragma clickScrollDelegate
-(void) clickOnPageForIndex:(NSNumber*) f_Index
{
    int tIndex = [f_Index intValue];  
    NSDictionary *dict = [parsedDataArray objectAtIndex:tIndex];	
	ProductListViewController *viewController = [[ProductListViewController alloc] initWithNibName:@"ProductListViewController" bundle:nil];
	viewController.hidesBottomBarWhenPushed = YES;
	viewController.cateID = [[dict objectForKey:kCateID] intValue];
    viewController.m_ListDataDic = dict;
    NSLog(@"cateID = %d",viewController.cateID);
    viewController.m_headimage = [dict objectForKey:@"image"];
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
								   initWithTitle:@"产品分类" 
								   style:UIBarButtonItemStylePlain 
								   target:self
								   action:nil];
	self.navigationItem.backBarButtonItem = backButton;
	//导航自带的动画
	[self.navigationController pushViewController:viewController animated:YES];
	[viewController release];
}

@end
